package de.jmda.mview.proj;

import java.util.HashSet;
import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import de.jmda.mview.DesktopPane;

/**
 * Hierarchical, tree like type for diagram groups.
 *
 * @author roger.jmda@gmail.com
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DiagramGroup
{
	public static String DEFAULT_NAME = "default diagram group";
	
	@XmlAttribute(required=true)
  private String name;

	@XmlTransient
  private DiagramGroup parentGroup;
	
	@XmlElementWrapper
  @XmlElements(@XmlElement(name="group"))
  private Set<DiagramGroup> childGroups = new HashSet<DiagramGroup>();

	@XmlElementWrapper
  @XmlElements(@XmlElement(name="diagram"))
  private Set<DesktopPane.JAXBModel> diagramModels =
  		new HashSet<DesktopPane.JAXBModel>();

	/**
	 * make JAXB happy
	 * <p>
	 * preserve this constructor for JAXB, do not call other constructors with
	 * default values
	 */
	private DiagramGroup()
  {
	  super();
  }

	public DiagramGroup(DiagramGroup parentGroup)
	{
		this(DEFAULT_NAME, parentGroup);
	}
	
	public DiagramGroup(String name, DiagramGroup parentGroup)
  {
	  this();
	  this.name = name;
	  this.parentGroup = parentGroup;
	  
	  if (parentGroup != null)
	  {
		  parentGroup.childGroups.add(this);
	  }

	  diagramModels.add((DesktopPane.createDefaultDesktopPane()).getJAXBModel());
  }

	public static DiagramGroup createDefaultDiagramGroup()
  {
	  return new DiagramGroup(DEFAULT_NAME, null);
  }
	
	public static boolean releaseDiagramGroup(DiagramGroup diagramGroup)
	{
		if (diagramGroup.parentGroup != null)
		{
			return diagramGroup.parentGroup.childGroups.remove(diagramGroup);
		}
		
		return false;
	}

	/**
	 * This method override is necessary to produce reasonable label text for
	 * JTree representation.
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
  public String toString()
  {
	  return name;
  }

	@XmlTransient
  public String getName()
  {
	  return name;
  }

	public void setName(String name)
  {
		this.name = name;
  }

	@XmlTransient
  public DiagramGroup getParentGroup()
  {
	  return parentGroup;
  }

	@XmlTransient
  public Set<DiagramGroup> getChildGroups()
  {
	  return childGroups;
  }

	@XmlTransient
  public Set<DesktopPane.JAXBModel> getDiagrams()
  {
	  return diagramModels;
  }
}